/* eslint-disable react-hooks/rules-of-hooks */
import './public-path';
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import '@/language';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import store, { persist } from '@/store';

let root: any;
function render(props: Record<string, any>) {
  const { container } = props;
  const dom = container
    ? container.querySelector('#root')
    : document.getElementById('root');
  root = ReactDOM.createRoot(dom);
  root.render(
    <Provider store={store}>
      <PersistGate persistor={persist}>
        <App {...props} />
      </PersistGate>
    </Provider>
  );
}

if (!window.__POWERED_BY_QIANKUN__) {
  render({});
}

// 微应用初始化只调用一次
export async function bootstrap(props: Record<string, any>) {
  console.log('react app bootstarp');
}

// 应用每次进入调用
export async function mount(props: Record<string, any>) {
  render(props);

  // dispatch(setGlobalItem(globalItem));
  // 监听变化
  // props.onGlobalStateChange((state: any, prev: any) => {
  //   console.log('状态变更前后', state, prev);
  //   // 将 state 存储到子应用自己的store中
  // });
  // 修改状态
  // props.setGlobalState(globalItem);
}

// 应用每次切出卸载调用，通常再次卸载微应用实例
export async function unmount(_props: Record<string, any>) {
  root.unmount();
}
